package com.jinshiji.newclient.com.jinshiji.newclient.service;

import android.support.annotation.IntegerRes;
import android.util.Log;
import android.util.Xml;
import android.widget.Toast;

import com.jinshiji.newclient.java.util.ArrayList.bean.NewsItem;

import org.xmlpull.v1.XmlPullParser;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wanshi on 2017/3/10.
 */
public class NewsInfoService {
    private static NewsItem newsItem;
    private static String TAG = "NewsInfoService";

    //创建集合存储数据
    public static List<NewsItem> getAllNews(String path) throws Exception {
        ArrayList<NewsItem> aList = new ArrayList<NewsItem>();
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(3000);
        int length = conn.getContentLength();

        String type = conn.getContentType();
        Log.i("conn", "服务器返回的资源长度为：" + length);
        Log.i("conn", "服务器返回的资源类型为：" + type);
        int code = conn.getResponseCode();
        Log.i(TAG,"响应码"+code);
        if (code == 200) { //失败码为404
            InputStream is = conn.getInputStream();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(is, "UTF-8");//??????????
            //xml的解析从头到尾
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) { //?
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        if ("item".equals(parser.getName())) {
                            newsItem = new NewsItem();
                        } else if ("title".equals(parser.getName())) {
                            newsItem.setTitle(parser.nextText());
                        } else if ("description".equals(parser.getName())) {
                            newsItem.setDescription(parser.nextText());
                        }else if ("image".equals(parser.getName())){
                            newsItem.setImage(parser.nextText());
                        }else if ("type".equals(parser.getName())){
                            newsItem.setType(parser.nextText());
                        }else if ("comment".equals(parser.getName())){
                            newsItem.setComment(Integer.parseInt(parser.nextText()));//类型强转
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if ("item".equals(parser.getName())){
                            aList.add(newsItem);
                        }
                        break;
                }
                eventType = parser.next();
            }
            return aList;
        } else {
            Log.i(TAG,"获取数据失败");
             return null;
        }
    }
}
